package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.widget.gridimg.AllEasyGridView;
import com.lzx.iteam.widget.gridimg.EasyGridView;
import com.lzx.iteam.widget.gridimg.ImageAdapter;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.MyMessage;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by mac on 15-6-18.
 * 模板编辑页面
 */
public class CustomEventActivity extends Activity implements View.OnClickListener, EasyGridView.IHandleGridView {


    private LinearLayout mBack;
    private ScrollView mSvCustomEventLayout;
    private LinearLayout mLlEventMember;
    private TextView mTvTitle;
    private TextView mTvPreView;
    private TextView mTvSave;
    private EditText mEtEventType;
    private TextView mEtEventMember;
    private EditText mEtEventTitle;
    private EditText mEtEventPart1;
    private EditText mEtEventPart2;
    private EditText mEtEventPart3;
    private ImageView mIvReAdd;
    private ImageView mIvReRight;
    private AllEasyGridView mEventReceiverGrid;
    private ImageAdapter adapter;

    private String mType;
    private String mMember;
    private String mTitle;
    private String mPart1;
    private String mPart2;
    private String mPart3;
    private String mEventTime;
    private String mEventId;
    private ArrayList<String> mPart;

    private CloudDBOperation mCloudDBOperation;
    private PreferenceUtil mPreferenceUtil;

    private final static int MAKE_TEMPLATES = 3001;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MAKE_TEMPLATES:
                    if (msg.arg1 == 0) {
                        JSONObject object = (JSONObject) msg.obj;
                        try {
                            mEventId = object.getString("tmp_event_id");
                            insertOrUpdataData(mEventId);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //setResult(RESULT_OK);
                        finish();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_event_layout_test);
        mCloudDBOperation = new CloudDBOperation(this);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        initView();
        getData();
    }

    public void initView() {
        mBack = (LinearLayout) findViewById(R.id.custom_event_ll_back);
        mTvPreView = (TextView) findViewById(R.id.custom_event_tv_preview);
        mTvSave = (TextView) findViewById(R.id.custom_event_tv_save);
        mTvTitle = (TextView) findViewById(R.id.custom_event_title);
        mEtEventType = (EditText) findViewById(R.id.custom_event_et_type);
        mEtEventMember = (TextView) findViewById(R.id.custom_event_et_member);
        mEtEventTitle = (EditText) findViewById(R.id.custom_event_et_title);
        mEtEventPart1 = (EditText) findViewById(R.id.custom_event_et_part1);
        mEtEventPart2 = (EditText) findViewById(R.id.custom_event_et_part2);
        mEtEventPart3 = (EditText) findViewById(R.id.custom_event_et_part3);
        mLlEventMember = (LinearLayout) findViewById(R.id.ll_custom_event_receiver);
        mEventReceiverGrid = (AllEasyGridView) findViewById(R.id.aegv_custom_event_receiver);
        mSvCustomEventLayout = (ScrollView) findViewById(R.id.sv_custom_event_layout);
        mIvReAdd = (ImageView) findViewById(R.id.custom_event_iv_add);
        mIvReRight = (ImageView) findViewById(R.id.custom_event_iv_right);

        mBack.setOnClickListener(this);
        mTvPreView.setOnClickListener(this);
        mTvSave.setOnClickListener(this);
        mIvReAdd.setOnClickListener(this);
        mLlEventMember.setOnClickListener(this);

    }

    public void getData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("event_msg");
        if (bundle != null) {
            mEventId = bundle.getString("event_tmp_id");
            mType = bundle.getString("event_type");
            mMember = bundle.getString("event_receiver");
            mTitle = bundle.getString("event_theme");
            mPart1 = bundle.getString("event_hint1");
            mPart2 = bundle.getString("event_hint2");
            mPart3 = bundle.getString("event_hint3");
            //mEventTime = bundle.getString("event_time");
            Log.d("receiver_back",mEventId  +  mMember + mType);

            if (!StringUtil.isEmpty(mType)) {
                mEtEventType.setText(mType);
            }
            if (!StringUtil.isEmpty(mTitle)) {
                mEtEventTitle.setText(mTitle);
            }
            if (!StringUtil.isEmpty(mPart1)) {
                mEtEventPart1.setText(mPart1);
            }
            if (!StringUtil.isEmpty(mPart2)) {
                mEtEventPart2.setText(mPart2);
            }
            if (!StringUtil.isEmpty(mPart3)) {
                mEtEventPart3.setText(mPart3);
            }
            ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
            if (!StringUtil.isEmpty(mMember)) {
                StringBuilder sb = new StringBuilder();
                try {
                    JSONArray jsonArray = new JSONArray(mMember);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        sb.append(jsonObject.get("user_name") + ",");
                        map.put("text", jsonObject.get("user_name"));
                        map.put("user_id", jsonObject.getString("user_id"));
                        map.put("icon", jsonObject.get("user_image").toString());
                        list.add(map);
                    }
                    mEtEventMember.setText(sb.substring(0, sb.length() - 1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            adapter = new ImageAdapter(CustomEventActivity.this, true);
            mEventReceiverGrid.initData(false, list, adapter);
            mEventReceiverGrid.setHandleGridView(CustomEventActivity.this);

            // 判断是不是事件模板的例子，例子只可预览不能进行其他操作
            /*if ( mEventTime != null && mEventTime.equals("你猜")){
                mEtEventType.setEnabled(false);
                mEtEventTitle.setEnabled(false);
                mEtEventPart1.setEnabled(false);
                mEtEventPart2.setEnabled(false);
                mEtEventPart3.setEnabled(false);
                mIvReAdd.setEnabled(false);
                mTvSave.setEnabled(false);
            }*/

        }

        if (mEtEventMember.getText().toString().trim().length() > 0) {
            mIvReRight.setVisibility(View.VISIBLE);
            mIvReAdd.setVisibility(View.GONE);
        } else {
            mIvReRight.setVisibility(View.GONE);
            mIvReAdd.setVisibility(View.VISIBLE);
        }
    }

    // 获取目前的数据
    public void getContent() {
        mType = mEtEventType.getText().toString().trim();
//        mMember = mEtEventMember.getText().toString().trim();
        mTitle = mEtEventTitle.getText().toString().trim();
        mPart1 = mEtEventPart1.getText().toString().trim();
        mPart2 = mEtEventPart2.getText().toString().trim();
        mPart3 = mEtEventPart3.getText().toString().trim();
        mPart = new ArrayList<String>();
        if (!StringUtil.isEmpty(mPart1)){
            mPart.add(mPart1);
        }
        if (!StringUtil.isEmpty(mPart2)){
            mPart.add(mPart2);
        }
        if (!StringUtil.isEmpty(mPart3)){
            mPart.add(mPart3);
        }

    }

    /**
     * 插入或者更新模板数据库
     */
    public void insertOrUpdataData(String eventId) {

        EventListData data = new EventListData();
//        data.setEventWhere("1");
        data.setUserId(mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID,""));
        data.setEventId(eventId);
        data.setEventName(mType);
        data.setEventTitle(mTitle);
        data.setReceiver(mMember);
        if ( mPart.size() == 3){
            data.setInitTitle1(mPart.get(0));
            data.setInitTitle2(mPart.get(1));
            data.setInitTitle3(mPart.get(2));
        }else if (mPart.size() == 2){
            data.setInitTitle1(mPart.get(0));
            data.setInitTitle2(mPart.get(1));
        }else if (mPart.size() == 1){
            data.setInitTitle1(mPart.get(0));
        }
        if (mCloudDBOperation.queryEventModelById(eventId)){
            mCloudDBOperation.updataEventModel(eventId,data);
        }else{
            mCloudDBOperation.insertEventModel(data);
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.custom_event_ll_back:
                if (mEventReceiverGrid.getVisibility() == View.VISIBLE) {
                    mEventReceiverGrid.setVisibility(View.GONE);
                    mSvCustomEventLayout.setVisibility(View.VISIBLE);
                    mTvTitle.setText("模板编辑");
                } else {
                    finish();
                }
                break;
            case R.id.custom_event_tv_preview:
                Intent intent = new Intent(this, CreateNewEventActivity.class);
                getContent();
                Bundle bundle = new Bundle();
                bundle.putString("type", "5");
                bundle.putString("event_type", "发" + mType);
                bundle.putString("event_theme", mTitle);
                bundle.putString("event_receiver", mMember);

                if (mPart.size() == 3){
                    bundle.putString("event_hint1", mPart.get(0));
                    bundle.putString("event_hint2", mPart.get(1));
                    bundle.putString("event_hint3", mPart.get(2));
                }else if (mPart.size() == 2){
                    bundle.putString("event_hint1", mPart.get(0));
                    bundle.putString("event_hint2", mPart.get(1));
                    bundle.putString("event_hint3", "");
                }else if (mPart.size() == 1){
                    bundle.putString("event_hint1", mPart.get(0));
                    bundle.putString("event_hint2", "");
                    bundle.putString("event_hint3", "");
                }else if (mPart.size() == 0){
                    bundle.putString("event_hint1", "");
                    bundle.putString("event_hint2", "");
                    bundle.putString("event_hint3", "");
                }

                bundle.putBoolean("is_show", true);
                intent.putExtra("event_msg", bundle);
                if (StringUtil.isEmpty(mType)) {
                    Toast.makeText(this, "事件类型不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    startActivity(intent);
                }
                break;
            case R.id.custom_event_iv_right:
                break;
            case R.id.custom_event_tv_save:
                getContent();
                if (StringUtil.isEmpty(mType)) {
                    Toast.makeText(this, "事件类型不能为空", Toast.LENGTH_SHORT).show();
                } else if (StringUtil.isEmpty(mEventId) && mCloudDBOperation.queryEventByType(mType)){
                    Toast.makeText(this, "已有此事件类型，请重新填写类型", Toast.LENGTH_SHORT).show();
                }else if (!StringUtil.isEmpty(mEventId) && mCloudDBOperation.queryEventByType(mType) && !mCloudDBOperation.findEventModeByEventId(mEventId).getEventName().equals(mType)){
                    Toast.makeText(this, "已有此事件类型，请重新填写类型", Toast.LENGTH_SHORT).show();
                }else{
                    sendMessage();
                }
                break;
            case R.id.custom_event_iv_add:
                ((DialerApp) getApplication()).setmEventToWhere("2");
                getContent();
                Intent intent1 = new Intent(CustomEventActivity.this, ChooseContactByTeamActivity.class);
                intent1.setAction("events_add_receiver");
                Bundle bundle1 = new Bundle();
                bundle1.putString("type", "5");
                bundle1.putString("event_type", mType);
                if (StringUtil.isEmpty(mMember)) {
                    bundle1.putString("event_receiver", "");
                } else {
                    bundle1.putString("event_receiver", mMember);
                }
                bundle1.putString("event_tmp_id",mEventId);
                bundle1.putString("event_theme", mTitle);
                bundle1.putString("event_hint1", mPart1);
                bundle1.putString("event_hint2", mPart2);
                bundle1.putString("event_hint3", mPart3);
                intent1.putExtra("event_msg", bundle1);
                startActivity(intent1);
                break;
            case R.id.ll_custom_event_receiver:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (mEtEventMember.getText().toString().trim().length() > 0) {
                    mTvTitle.setText("收件人");
                    mSvCustomEventLayout.setVisibility(View.GONE);
                    mEventReceiverGrid.setVisibility(View.VISIBLE);
                }
                break;
        }
    }


    public void sendMessage() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TMP_EVENT_ID, mEventId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TEMP_NAME, mType));

        if (!StringUtil.isEmpty(mMember)) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_UIDS, mMember));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TITLE, mTitle));
        JSONArray contents = new JSONArray();
        if (!StringUtil.isEmpty(mPart1)) {
            JSONObject part1 = new JSONObject();
            try {
                part1.put("init_title", mPart1);
                contents.put(part1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        if (!StringUtil.isEmpty(mPart2)) {
            JSONObject part2 = new JSONObject();
            try {
                part2.put("init_title", mPart2);
                contents.put(part2);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        if (!StringUtil.isEmpty(mPart3)) {
            JSONObject part3 = new JSONObject();
            try {
                part3.put("init_title", mPart3);
                contents.put(part3);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_CONTENTS, contents.toString()));
        MyMessage.MakeCustomModelMessage message = new MyMessage.MakeCustomModelMessage(mHandler.obtainMessage(MAKE_TEMPLATES));
        message.mApi = AsynHttpClient.API_EVENT_MAKE_TEMPLATES;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);

    }

    @Override
    public void addImage() {
        ((DialerApp) getApplication()).setmEventToWhere("2");
        getContent();
        Intent intent1 = new Intent(CustomEventActivity.this, ChooseContactByTeamActivity.class);
        intent1.setAction("events_add_receiver");
        Bundle bundle1 = new Bundle();
        bundle1.putString("type", "5");
        bundle1.putString("event_type", mType);
        if (StringUtil.isEmpty(mMember)) {
            bundle1.putString("event_receiver", "");
        } else {
            bundle1.putString("event_receiver", mMember);
        }
        bundle1.putString("event_tmp_id",mEventId);
        bundle1.putString("event_theme", mTitle);
        bundle1.putString("event_hint1", mPart1);
        bundle1.putString("event_hint2", mPart2);
        bundle1.putString("event_hint3", mPart3);
        intent1.putExtra("event_msg", bundle1);
        startActivity(intent1);
    }

    @Override
    public void delImage(int position) {
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        StringBuilder sb = new StringBuilder();
        try {
            JSONArray jsonArray = new JSONArray(mMember);
            JSONArray newJsonArray = new JSONArray();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (!jsonObject.get("user_id").equals((String) mEventReceiverGrid.getData().get(position).get("user_id"))) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    newJsonArray.put(jsonObject);
                    sb.append(jsonObject.get("user_name") + ",");
                    map.put("text", jsonObject.get("user_name"));
                    map.put("icon", jsonObject.get("user_image").toString());
                    map.put("user_id", jsonObject.getString("user_id"));
                    list.add(map);
                } else if ("0".equals(jsonObject.get("user_id"))) {
                    if (!jsonObject.get("user_name").equals((String) mEventReceiverGrid.getData().get(position).get("text"))) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        newJsonArray.put(jsonObject);
                        sb.append(jsonObject.get("user_name") + ",");
                        map.put("text", jsonObject.get("user_name"));
                        map.put("icon", jsonObject.get("user_image").toString());
                        map.put("user_id", jsonObject.getString("user_id"));
                        list.add(map);
                    }
                }
            }
            if (sb.length() > 0) {
                mEtEventMember.setText(sb.substring(0, sb.length() - 1));
            } else {
                mEtEventMember.setText("");
                mIvReAdd.setVisibility(View.VISIBLE);
                mIvReRight.setVisibility(View.GONE);
            }
            if (newJsonArray.length() == 0){
                mMember = "";
            }else{
                mMember = newJsonArray.toString();
            }
            adapter = new ImageAdapter(CustomEventActivity.this, true);
            mEventReceiverGrid.initData(false, list, adapter);
            mEventReceiverGrid.setHandleGridView(CustomEventActivity.this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void queryImage(int position) {

    }
}
